import { Button, Form, Input, message, Modal, Radio, Select, Space } from 'antd';
import { useState } from 'react';

import scheduleService from '@/api/services/stars/scheduleService';

import CronModal from './cron-modal';
import { ScheduleType } from './type';

import { ModalProps } from '#/entity';
import { JobGroupTypeMapText, misfirePolicyMapText } from '#/publicVariable';

export function ScheduleModal({
  title,
  show,
  formValue,
  onOk,
  onCancel,
}: ModalProps<ScheduleType>) {
  const [form] = Form.useForm();
  const onFinish = (values: any) => {
    const transData = {
      ...values,
    };
    if (formValue.jobId) {
      scheduleService.updateSchedule(formValue.jobId, transData).then(() => {
        message.success(`任务 ${values.jobName} 更新成功`);
        onOk();
      });
    } else {
      scheduleService.createSchedule(transData).then(() => {
        message.success(`任务 ${values.jobName} 创建成功`);
        onOk();
      });
    }
  };
  const [cronModalProps, setCronModalProps] = useState<ModalProps<ScheduleType>>({
    title: '',
    show: false,
    onOk: (express) => {
      setCronModalProps((prev) => ({
        ...prev,
        show: false,
      }));
      console.log(express);
      form.setFieldsValue({
        cronExpression: express,
      });
    },
    onCancel: () => {
      setCronModalProps((prev) => ({
        ...prev,
        show: false,
      }));
    },
    formValue: {
      value: formValue.cronExpression,
    },
  });
  const onClickCron = () => {
    setCronModalProps((prev) => ({
      ...prev,
      title: 'cron表达式生成器',
      show: true,
      formValue: {
        ...formValue,
        misfirePolicy: 1,
        concurrent: 1,
      },
    }));
  };
  // ______________________________________________________________
  const num = 10000;
  const effectiveFigure = {
    // 校验二维码宽度是否有效
    pattern: /^\d+$/,
    message: '只能输入数字',
  };
  const effectiveFigureNum = {
    validator: (_, value) => {
      if (value > num) {
        return Promise.reject(new Error(`排序数字不能超过${num}`));
      }
      return Promise.resolve();
    },
  };
  const nameWidth = 64;
  const redirectUrlWidth = 128;
  const modalRender = (dom: React.ReactNode) => (
    <Form
      initialValues={formValue}
      form={form}
      labelCol={{ span: 5 }}
      wrapperCol={{ span: 17 }}
      onFinish={onFinish}
      clearOnDestroy
      layout="horizontal"
      // layout="vertical"
    >
      {dom}
    </Form>
  );
  // invokeTarget; status;  jobName,; jobGroup;

  return (
    <Modal
      width={700}
      title={title}
      open={show}
      onCancel={onCancel}
      okButtonProps={{ autoFocus: true, htmlType: 'submit' }}
      destroyOnClose
      modalRender={modalRender}
    >
      <Form.Item name="jobName" label="任务名称" rules={[{ required: true }]}>
        <Input showCount maxLength={nameWidth} />
      </Form.Item>
      <Form.Item name="jobGroup" label="任务组名" rules={[{ required: true }]}>
        <Select>
          {Object.entries(JobGroupTypeMapText).map(([value, label]) => (
            <Select.Option key={value} value={value}>
              {label}
            </Select.Option>
          ))}
        </Select>
      </Form.Item>
      <Form.Item name="invokeTarget" label="调用目标字符串" rules={[{ required: true }]}>
        <Input />
      </Form.Item>

      <Form.Item name="misfirePolicy" label="执行策略" rules={[{ required: true }]}>
        <Radio.Group
          block
          buttonStyle="solid"
          optionType="button"
          options={Object.entries(misfirePolicyMapText).map(([value, label]) => ({ value, label }))}
        />
      </Form.Item>

      <Form.Item name="concurrent" label="是否允许并发" rules={[{ required: true }]}>
        <Radio.Group
          block
          buttonStyle="solid"
          optionType="button"
          options={[
            { value: 0, label: '允许' },
            { value: 1, label: '禁止' },
          ]}
        />
      </Form.Item>

      <Form.Item name="cronExpression" label="cron执行表达式" rules={[{ required: true }]}>
        <Space.Compact style={{ width: '100%' }}>
          <Input
            defaultValue={formValue.cronExpression}
            value={form.getFieldValue('cronExpression')}
            onChange={(e) => {
              form.setFieldsValue({
                cronExpression: e.target.value,
              });
            }}
          />
          <Button type="primary" onClick={onClickCron}>
            生成cron执行表达式
          </Button>
        </Space.Compact>
      </Form.Item>
      <Form.Item name="remark" label="备注">
        <Input.TextArea />
      </Form.Item>
      <CronModal {...cronModalProps} />
    </Modal>
  );
}
